<?php
// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// 图片目录路径 (根据实际情况修改)
$imageDir = '/var/www/html/picture/';
$baseUrl = 'http://8.138.215.14/picture/';

$response = [
    'success' => false,
    'message' => '',
    'images' => []
];

try {
    // 检查目录是否存在
    if (!is_dir($imageDir)) {
        throw new Exception("图片目录不存在");
    }

    // 获取所有图片文件
    $files = glob($imageDir . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
    
    if (empty($files)) {
        $response['message'] = '目录中没有图片';
    } else {
        // 按修改时间倒序排序
        usort($files, function($a, $b) {
            return filemtime($b) - filemtime($a);
        });

        foreach ($files as $file) {
            $filename = basename($file);
            $response['images'][] = [
                'name' => $filename,
                'url' => $baseUrl . rawurlencode($filename),
                'size' => formatSize(filesize($file)),
                'date' => date("Y-m-d H:i", filemtime($file)),
                'alt' => pathinfo($filename, PATHINFO_FILENAME)
            ];
        }
        $response['success'] = true;
    }
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);

// 格式化文件大小
function formatSize($bytes) {
    if ($bytes >= 1073741824) {
        return round($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return round($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return round($bytes / 1024) . ' KB';
    } else {
        return $bytes . ' B';
    }
}
?>